import { UploadIcon } from '@/components/bs-icons/upload'
import { aiIconGenerateApi, getSignUrl, uploadFile } from '@/controllers/API/common'
import axios from '@/controllers/request'
import { useDictStore } from '@/store/dictStore'
import { blobToArrayBuffer, convertBase64ToBlob } from '@/util/utils'
import { generateUUID } from '@/utils'
import { LoadingOutlined } from '@ant-design/icons'
import type { UploadProps } from 'antd'
import { Divider, Segmented, Upload } from 'antd'
import { t } from 'i18next'
import React, { useEffect, useState } from 'react'
import { showMessage } from '../message'
import './index.css'

type Align = '上传' | '通用' | 'AI生成'

function isImageFile(file) {
  const fileName = file.name
  const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase()
  return extension === 'png' || extension === 'jpg' || extension === 'jpeg'
}

const App = ({
  defaultFileList = [],
  logo = '',
  onSelect,
  setDefault = val => {},
  form = null, // 外层使用form校验时直接传入form
  validateNames = [], // 按名称和描述顺序传入
  name = '',
  description = '',
  validateMethod = undefined, // 外层非form校验时传入名称和描述，并传入外层定义的校验函数
  ...props
}) => {
  const [alignValue, setAlignValue] = React.useState<Align>('上传')
  const [logoUrl, setLogoUrl] = React.useState(logo)
  const [ailogoUrl, setAilogoUrl] = React.useState('')
  const { loadDictOptions } = useDictStore()

  const { Dragger } = Upload

  const [typeList, setTypeList] = React.useState<any[]>([])
  // ai loading
  const [AICreateLoading, setAICreateLoading] = useState(false)

  /* 通用  ai */
  const initData = (type = 'icon') => {
    loadDictOptions(type).then(res => {
      setTypeList(res)
      if (res && res.length) {
        setDefault(res[0].value)
      }
    })
  }

  const generateAiIcon = () => {
    if (form) {
      form
        .validateFields(validateNames)
        .then(values => {
          setAICreateLoading(true)
          console.log('form validateFields values', values)
          getAiIconBase64Info(values[validateNames[0]], values[validateNames[1]])
        })
        .catch(err => {
          console.log('err', err)
          setAICreateLoading(false)
        })
    } else if (validateMethod) {
      const status = validateMethod()
      console.log('validateMethod status', status)
      if (status) {
        setAICreateLoading(true)
        getAiIconBase64Info(name, description)
      } else {
        setAICreateLoading(false)
      }
    } else {
      setAICreateLoading(false)
    }
  }

  const getAiIconBase64Info = (name, description) => {
    const iconInfo = {
      name,
      description,
      width: 512,
      height: 512
    }
    aiIconGenerateApi(iconInfo)
      .then(res => {
        uploadBase64Img(res.image)
      })
      .catch(err => {
        console.log(err)
        setAICreateLoading(false)
      })
  }

  const uploadBase64Img = async (base64Str: string) => {
    try {
      const fileName = generateUUID(32) + '.png'
      let { url, preview_url } = await getSignUrl(fileName)
      window.location.origin.startsWith('https') && (url = url.replace('http://', 'https://'))

      const fileBlob = convertBase64ToBlob(base64Str)
      blobToArrayBuffer(fileBlob, arrayBuffer => {
        uploadFile(url, arrayBuffer)
          .then(res => {})
          .finally(() => {
            setAICreateLoading(false)
            setAilogoUrl(preview_url)
            // setLogoUrl(preview_url)
          })
      })
    } catch (error) {
      console.log(error)
      setAICreateLoading(false)
    }
  }

  useEffect(() => {
    initData()
    if (alignValue == 'AI生成' && !ailogoUrl) {
      generateAiIcon()
    }
  }, [alignValue])

  useEffect(() => {
    setLogoUrl(logo)
  }, [logo])

  useEffect(() => {
    onSelect(logoUrl)
  }, [logoUrl])

  const uploadImage = async options => {
    const { onSuccess, onError, file, onProgress } = options

    try {
      const formData = new FormData()
      formData.append('file', file)
      const response: any = await axios.post('/api/v1/common/upload/icon', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      console.log('文件上传成功:', response)
      setLogoUrl(response?.file_path)
      onSuccess({ file, preview_url: response?.file_path })
    } catch (err) {
      console.error('Error uploading file:', err)
      onError({ err })
    }
  }

  const [kFileList, setKFileList] = useState([])

  const UploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    maxCount: 1,
    defaultFileList,
    accept: '.png, .jpg, .jpeg',
    customRequest: uploadImage,
    // beforeUpload: file => {
    //   // 文件上传前校验
    //   if (file.size > 10240000) {
    //     message.error(`文件过大，请重新选择10M以内的文件`)
    //     return Upload.LIST_IGNORE
    //   } else {
    //     return true
    //   }
    // },
    onChange(info) {
      const { status } = info.file
      if (status !== 'uploading') {
        // console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        // onSelect(info.file.response.data.file_path)
        // message.success(`${info.file.name} file uploaded successfully.`)
      } else if (status === 'error') {
        // message.error(`${info.file.name} file upload failed.`)
      }

      const realFiles = info.fileList
        .filter(file => file.status)
        .map(item => {
          if (item.error) {
            item.error.message = 'Upload Failed'
          }
          return item
        })
      setKFileList(realFiles)
    },
    beforeUpload: file => {
      const isLt50KB = file.size / 1024 < 500

      if (!isLt50KB) {
        showMessage({
          content: `图片: ${file.name} 超过500k，请重新上传`,
          type: 'error'
        })
      }

      const isImg = isImageFile(file)
      if (!isImg) {
        showMessage({
          content: `${file.name} 格式错误，请上传.png, .jpg, .jpeg格式的图片`,
          type: 'error'
        })
      }

      return isLt50KB && isImg
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files)
    },
    onRemove: file => {
      defaultFileList = []
      setLogoUrl('')
    }
  }

  return (
    <>
      <span className="plugin-family "> icon</span>
      <Divider className="ml-[14px] mr-[14px]" type="vertical" />
      <Segmented
        defaultValue="上传"
        style={{ marginBottom: 8 }}
        onChange={value => setAlignValue(value as Align)}
        options={['上传', '通用']}
        // options={['上传', '通用', 'AI生成']}
        className="Segmented_font"
      />
      {alignValue == '上传' && (
        <div className="common-icon-upload-container" style={{ marginTop: '16px' }}>
          <Dragger {...UploadProps} fileList={kFileList}>
            <p className="ant-upload-drag-icon mb-[13px] text-center">
              <UploadIcon className="inline-block group-hover:text-primary" />
            </p>
            <p className="common-upload-sub-text text-[14px]">{t('code.clickOrDragHere')}</p>
          </Dragger>
        </div>
      )}
      {alignValue == '通用' && (
        <div style={{ marginTop: '16px' }}>
          {typeList.map((item, index) => (
            <img
              key={index}
              className="mb-[10px] mr-[10px] inline-block cursor-pointer hover:bg-nav-hover"
              width={32}
              height={32}
              src={item.value}
              onClick={() => setLogoUrl(item.value)}
            />
          ))}
        </div>
      )}
      <div className="flexRowStart mt-[10px]">
        <span className="flexRowStart">
          <span className="iconUploadTitle">当前选中：</span>
          {/* {logoUrl && <Image className="select inline-block" src={logoUrl} />} */}
          {logoUrl && <img className="iconUploadImg" src={logoUrl} />}
        </span>
        {/* 展示生成ai图 */}
        {alignValue == 'AI生成' && (
          <span className="flexRowStart" style={{ margin: '0 16px' }}>
            <span className="iconUploadTitle">生成结果：</span>
            {ailogoUrl && (
              <img
                className="cursonCase iconUploadImg"
                onClick={() => {
                  setLogoUrl(ailogoUrl)
                }}
                src={ailogoUrl}
              />
            )}
          </span>
        )}
        {/* ai生成 */}
        {alignValue == 'AI生成' && (
          <span
            onClick={() => {
              generateAiIcon()
            }}
            className={AICreateLoading ? 'aiIconCase aiIconCase_loading' : 'aiIconCase flexRow cursonCase'}
          >
            {AICreateLoading && <LoadingOutlined style={{ marginRight: '5px' }} />}
            {AICreateLoading ? '生成中' : '重新生成'}
          </span>
        )}
      </div>
    </>
  )
}

export default App
